package com.graduationproject.examonline.schoolClass.controller;

import com.graduationproject.examonline.exam.entity.Exam;
import com.graduationproject.examonline.exam.mapper.ExamMapper;
import com.graduationproject.examonline.schoolClass.service.ClassService;
import com.graduationproject.examonline.student.entity.Student;
import com.graduationproject.examonline.student.mapper.StudentMapper;
import com.graduationproject.examonline.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("api/class")
public class ClassController {

    @Autowired
    private ClassService classService;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private ExamMapper examMapper;

    @GetMapping("/findAllClass")
    public Result findAllClass() {
        return classService.findAllClass();
    }

    @GetMapping("/deleteClassById")
    public Result deleteClassById(String class_id) {
        Map<String, Object> p = new HashMap<String, Object>();
        p.put("class_id", class_id);
        p.put("next_class_id", class_id + "_deleted_" + new Date().getTime());
        p.put("deleted", 1);
        List<Student> studentList = studentMapper.findStudentByClassId(class_id);
        List<Exam> examList = examMapper.getExamListByClassId(class_id);
        if (studentList.size() > 0 || examList.size() > 0) {
            return new Result(1, 200, "修改失败,外键约束");
        } else {
            return classService.updateById(p);
        }
    }

    @PostMapping("/updateClassById")
    public Result updateClassById(@RequestBody Map<String, Object> p) {
        Result r = classService.updateById(p);
        if (r.getStatus() == 0) {
            List<Student> studentList = studentMapper.findStudentByClassId((String) p.get("class_id"));
            List<Exam> examList = examMapper.getExamListByClassId((String) p.get("class_id"));
            for (int i = 0; i < studentList.size(); i++) {
                Map<String, Object> pp = new HashMap<String, Object>();
                pp.put("stuId", studentList.get(i).getStu_id());
                pp.put("classId", p.get("next_class_id"));
                studentMapper.editStudentById(pp);
            }
            for (int i = 0; i < examList.size(); i++) {
                Map<String, Object> pp = new HashMap<String, Object>();
                pp.put("exam_id", examList.get(i).getExam_id());
                pp.put("class_id", examList.get(i).getClass_id().replace((String) p.get("class_id"), (String) p.get("next_class_id")));
                examMapper.updateExamById(pp);
            }
        }
        return r;
    }

    @GetMapping("/insertClass")
    public Result insertClass(String class_id) {
        return classService.insertClass(class_id);
    }
}
